package com.lkm.app_ui.m.Imple.order_0;

import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;

import com.lkm.app_ui.AppConfig;
import com.lkm.app_ui.AppConst;
import com.lkm.app_ui.log.AppLogger;
import com.lkm.app_ui.m.order_0.Order0Module;
import com.lkm.app_ui.m.order_img.OrderImgModule;
import com.lkm.frame.otto.LinkBus;
import com.lkm.frame.otto.LinkBusEventFlag;
import com.lkm.frame.otto.ObserverAutoNext;
import com.lkm.javatool.CollectionHelp;
import com.lkm.javatool.StringHelp;
import com.lkm.javatool.lang.RunnablePR;
import com.lkm.market2_0.entity.SteelyardInfo;
import com.lkm.market2_0.m.steelyarddata.OnOrderAddEvent;
import com.lkm.market2_0.m.steelyarddata.OnSteelardInfoLoadEvent;
import com.lkm.market2_0.m.steelyarddata.OrderEntity;
import com.lkm.market2_0.m.steelyarddata.SteelyardDataModule;
import com.lkm.market2_0.m.steelyardserver.event.OnWeightInfoChangeEvent;

import java.util.ArrayList;
import java.util.List;



public class Order0ModuleImpl implements Order0Module {

    private UsePrice usePrice;
    private UseWeight useWeight;
    private boolean isTackImg = false;
    

    public Order0ModuleImpl(SteelyardDataModule dataManager) {
        this.dataManager = dataManager;
        this.mainHandler = new Handler(Looper.getMainLooper());
        usePrice = new UsePrice(dataManager) {
            @Override
            protected void requestSaveOrder(String steelyardMac) {
                Order0ModuleImpl.this.requestSaveOrder(steelyardMac);
            }
        };
        useWeight = new UseWeight(dataManager) {
            @Override
            protected void requestSaveOrder(String steelyardMac) {
                Order0ModuleImpl.this.requestSaveOrder(steelyardMac);
            }
        };


        reOnOrderAddEvent();
        reOnStee();
    }

    SteelyardDataModule dataManager;
    Handler mainHandler;
    
    private int tackImgWaitTime = 2000;

    private void reOnStee(){
        LinkBus.registerReceiver(new ObserverAutoNext<OnSteelardInfoLoadEvent>() {
            @Override
            public void onReceiver(OnSteelardInfoLoadEvent data) {
                SteelyardInfo steelyardInfo = data.getSteelyardInfo();
                
                
                
                
                String order0Config = steelyardInfo.upDataApiTo == null ? "" : steelyardInfo.upDataApiTo.order0Config;
                if(order0Config == null)order0Config = "";

                order0Config = order0Config.toLowerCase();
                boolean isUseWeight = order0Config.contains("w");
                boolean isUsePrice = order0Config.contains("p");
                boolean isTackImg_ = order0Config.contains("c");;
                boolean isSpee =  order0Config.contains("s");;

                isTackImg = isTackImg_;
                int delayTime = isSpee? 1000: 2000;
                
                if(isTackImg)delayTime = tackImgWaitTime + 200;
                if(isUsePrice)
                    usePrice.start(delayTime);
                else
                    usePrice.stop();

                if(isUseWeight)
                    useWeight.start(delayTime);
                else
                    useWeight.stop();

            }

            @Override
            public Class getBusEventClass() {
                return OnSteelardInfoLoadEvent.class;
            }
        });
    }

    private void requestSaveOrder(String steelyardMac) {
        AppLogger.Order.requestSaveOrder0();

        











        
        OrderEntity orderEntity = dataManager.onlyCreateOrderEntity(steelyardMac, orderHanler);

        if(orderEntity==null||orderEntity.totalPrice==0)return;

        if(StringHelp.isEmpty(orderEntity.orderNum))return;

//        orderEntity.orderNum = "B"+orderEntity.orderNum;
        orderEntity.type = OrderEntity.TYPE_NotFull0;
        AppLogger.Order.temp("临时订单"+orderEntity.orderNum );


        // 这里替换一下orderEntity.goods，让他保证没有小计的数据。因为orderEntity.goods可能来自SaleCacheInfo.goodEntities，跟UI上共用对象了（OrderEntity.GoodEntity），会导致UI列表中的商品也被拿出来。
        OrderEntity.GoodEntity goodEntity = dataManager.getCurWeightChangeGood(steelyardMac);
        List<OrderEntity.GoodEntity> goods = new ArrayList<>();
        if(goodEntity!=null) {
            goods.add(goodEntity);
        }
        
        orderEntity = OrderEntity.createOrderEntity(orderEntity.steelyardMac,orderEntity.type,orderEntity.createTime,goods,orderEntity.orderNum);

        if(orderEntity==null||orderEntity.totalPrice==0)return;


        if (!CollectionHelp.isEmpty(orderEntity.getGoods())) {
//            AppLogger.Order.temp("===sz"+CollectionHelp.getSize(orderEntity.goods) + orderEntity.goods.get(0).img_on);
            OrderEntity orderEntityWatiSave = orderEntity;

            
            if(preOrderEntityWatiSave != null) {


                OrderImgModule orderImgModule = isTackImg? AppConst.getModuleManager().peekModule(OrderImgModule.class):null;
                if (orderImgModule != null) {
                    orderImgModule.requestTackImg(preOrderEntityWatiSave.getGoods().get(0), false);
                    mainHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            AppLogger.Order.requestSaveOrder0OK();

                            if(preOrderEntityWatiSave!=null)
                            dataManager.saveOrderEntity(steelyardMac, preOrderEntityWatiSave);
                        }
                        
                        
                        
                    }, tackImgWaitTime);
                }else{

                AppLogger.Order.requestSaveOrder0OK();
                dataManager.saveOrderEntity(steelyardMac, preOrderEntityWatiSave);
                }
            }
            preOrderEntityWatiSave = orderEntityWatiSave;

        }
    }
    
    private void reOnOrderAddEvent(){
        LinkBus.registerReceiver(new ObserverAutoNext<OnOrderAddEvent>() {
            @Override
            public void onReceiver(OnOrderAddEvent data) {
                


                    if (data.getOrderEntity().isFullOrder()) {
                        preOrderEntityWatiSave = null;
                    }
            }

            @Override
            public Class getBusEventClass() {
                return OnOrderAddEvent.class;
            }
        });
    }
    
    private OrderEntity preOrderEntityWatiSave = null;
    RunnablePR<String ,String> orderHanler = new RunnablePR<String, String>() {
        @Override
        public String run(String s) {
            return "B"+s;
        }
    };
}
